package com.efounder.forwechat;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;

import androidx.multidex.MultiDex;

import com.efounder.BaseApplication;
import com.efounder.chat.service.OSPService;
import com.efounder.chat.service.WakeReceiver;
import com.efounder.chat.service.WatchReceiver;
import com.efounder.chat.service.WatchService;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.manager.ThemeManager;
import com.efounder.frame.utils.Constants;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.http.EFHttpRequest;
import com.efounder.util.ActivityTaskManager;
import com.efounder.util.MobilePushUtils;
import com.marswin89.marsdaemon.DaemonClient;
import com.marswin89.marsdaemon.DaemonConfigurations;
import com.tencent.smtt.sdk.QbSdk;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ReflectUtils;
import com.utilcode.util.Utils;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;

import me.yokeyword.fragmentation.Fragmentation;
import me.yokeyword.fragmentation.helper.ExceptionHandler;

import static com.efounder.chat.model.Constant.SKIN_DIR;


public class BaseApp extends BaseApplication {

    private static final String TAG = "BaseApp"; /** 当前Activity **/

    /**
     * activity管理类
     */
    public static ActivityTaskManager actManager = ActivityTaskManager.getInstance(); // Activity管理类
    public static Context context;

    public static String UserInfo = "userinfo";
    private Map<String, Object> qxMap;

    //加载BreadWallet的SO文件
//    static {
//        try {
//            System.loadLibrary("core");
//        } catch (UnsatisfiedLinkError e) {
//            e.printStackTrace();
//            Log.d(TAG, "BreadWallet Native code library failed to load.\\n\" + " + e);
//        }
//    }

    /**
     * 移除相对应的activity
     *
     * @param curActivityTag
     */
    public static void exitActivity(String curActivityTag) {
        if (BaseApp.actManager.containsName(curActivityTag)) {
            BaseApp.actManager.removeActivity(curActivityTag);
        }
    }

    private DaemonClient mDaemonClient;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        Log.d("loadDex", "App attachBaseContext ");
        MultiDex.install(base);
    }

    private DaemonConfigurations createDaemonConfigurations() {
        DaemonConfigurations.DaemonConfiguration configuration1 = new DaemonConfigurations.DaemonConfiguration(
                "com.efounder.liveapp:gray", OSPService.class.getCanonicalName(), WakeReceiver.class.getCanonicalName()
        );

        DaemonConfigurations.DaemonConfiguration configuration2 = new DaemonConfigurations.DaemonConfiguration(
                "com.efounder.liveapp:remote", WatchService.class.getCanonicalName(), WatchReceiver.class.getCanonicalName()
        );

        DaemonConfigurations.DaemonListener listener = new MyDaemonListener();

        return new DaemonConfigurations(configuration1, configuration2, listener);
    }

    class MyDaemonListener implements DaemonConfigurations.DaemonListener {
        @Override
        public void onPersistentStart(Context context) {
        }

        @Override
        public void onDaemonAssistantStart(Context context) {
        }

        @Override
        public void onWatchDaemonDaed() {
        }
    }


    @Override
    public void onCreate() {
        super.onCreate();

        if (shouldInit()) {
//            Log.e(TAG,"shouldInit----------------------------");
            //初始化第三方
            initThirdService();
            //如果不支持推送，才初始化保活
            if (!MobilePushUtils.isSupportPush()) {
                mDaemonClient = new DaemonClient(createDaemonConfigurations());
                mDaemonClient.onAttachBaseContext(this);
            }
        }

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                EFFrameUtils.setCurrentActivity(activity);
            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {
                if (!activity.equals(EFFrameUtils.getCurrentActivity())) {
                    EFFrameUtils.setCurrentActivity(activity);
                }
            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

    private void initThirdService() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                //初始化换肤
                initSkinSupport(BaseApp.this);
                initVolley();
                try {
                    initTencentTbs();
                } catch (Exception e) {
                    Log.e(TAG, "腾讯tbs初始化失败");
                }
            }
        }.start();
        initBugly();
        initFresco();
        //工具类初始化com.utilcode.
        Utils.init(this);

        //初始化手机的push功能(反射实现)
        try {
            ReflectUtils reflectUtils = ReflectUtils.reflect("com.efounder.push.PushManager");
            reflectUtils.newInstance(this).method("initPush");
        } catch (Exception e) {
            // e.printStackTrace();
            LogUtils.d("未启用push功能");
        }
        // initFragmentation();

    }

    private void initFragmentation() {
        Fragmentation.builder()
                // 设置 栈视图 模式为 （默认）悬浮球模式   SHAKE: 摇一摇唤出  NONE：隐藏， 仅在Debug环境生效
                .stackViewMode(Fragmentation.BUBBLE)
                .debug(true) // 实际场景建议.debug(BuildConfig.DEBUG)
                /**
                 * 可以获取到{@link me.yokeyword.fragmentation.exception.AfterSaveStateTransactionWarning}
                 * 在遇到After onSaveInstanceState时，不会抛出异常，会回调到下面的ExceptionHandler
                 */
                .handleException(new ExceptionHandler() {
                    @Override
                    public void onException(Exception e) {
                        // 以Bugtags为例子: 把捕获到的 Exception 传到 Bugtags 后台。
                        // Bugtags.sendException(e);
                    }
                })
                .install();
    }

    //腾讯浏览服务，支持视频播放，文档在线浏览
    private void initTencentTbs() {
        EnvironmentVariable.setProperty("tbsLoadResult", "false");
        if (EnvironmentVariable.getProperty("initTbs", "0").equals("0")) {
            return;
        }
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean isX5Core) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.d("BaseApp", " initTencentTbs: onViewInitFinished is " + isX5Core);
                EnvironmentVariable.setProperty("tbsLoadResult", isX5Core + "");
            }

            @Override
            public void onCoreInitFinished() {
            }
        };
        //是否允许非wifi场景下下载内核
        QbSdk.setDownloadWithoutWifi(true);
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
    }

    /**
     * 初始化换肤控件
     */
    private void initSkinSupport(Application application) {
        ThemeManager.getInstance(application).initSkinSupport(SKIN_DIR);
    }

    private void initFresco() {
        // 初始化图片缓存库
        //Fresco.initialize(this);
    }

    @Override
    public void loadSettingProperties() {
        try {
            //判断是否是第一次打开应用
            String isFirst = EnvironmentVariable.getProperty("isFirst", "true");
            Properties properties = new Properties();
            properties.load(getAssets().open("setting.properties"));

            if ("true".equals(isFirst) || "true".equals(properties.getProperty(Constants.KEY_IS_RELOAD, "true"))) {
                Enumeration enumeration = properties.propertyNames();
                while (enumeration.hasMoreElements()) {
                    String key = (String) enumeration.nextElement();
                    String value = (String) properties.get(key);
//                    Log.e("-----", key + "-----" + value);
                    EnvironmentVariable.setProperty(key, value);
                }
                //初始化完成后 isFirst 设成 false
                EnvironmentVariable.setProperty("isFirst", "false");
                properties.setProperty(Constants.KEY_IS_RELOAD, "false");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化网络访问类 操作
     */
    private void initVolley() {
        EFHttpRequest.init(this);
    }

    public Map<String, Object> getQxMap() {
        return qxMap;
    }

    public void setQxMap(Map<String, Object> qxMap) {
        this.qxMap = qxMap;
    }


    //判断系统是否初始化结束；有些功能需要等待系统初始化结束后才能使用
    private boolean isSystemInited = false;

    public boolean isSystemInited() {
        return isSystemInited;
    }

    public void setSystemInited(boolean systemInited) {
        isSystemInited = systemInited;
    }


    @Override
    public void onTerminate() {
        // 程序终止的时候执行
        Log.i(TAG, "--------onTerminate");
        super.onTerminate();
    }

    @Override
    public void onLowMemory() {
        // 低内存的时候执行
        Log.i(TAG, "--------onLowMemory");
        super.onLowMemory();
    }

    @Override
    public void onTrimMemory(int level) {
        // 程序在内存清理的时候执行
        Log.i(TAG, "--------onTrimMemory");
        super.onTrimMemory(level);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.i(TAG, "--------onConfigurationChanged");
        super.onConfigurationChanged(newConfig);
    }
}
